<!-- 
  @author: 善良的YWJ
  @Created by shanliangdeYWJ on 2021/07/12 00:15:17
  @file: TodoItem.vue
  @description:
  ```
  TodoItem.vue
  
  重构组件要义之
  - 输入
  - 输出
  ```
  @link [Github](https://github.com/shanliangdeYWJ)
-->

<template>
  <li
    class="todo-item"
    :class="{
      completed: todo.completed,
      editing: todo === editedTodo,
    }"
  >
    <!-- 绑定完成状态 -->
    <div class="view">
      <input v-model="todo.completed" type="checkbox" />
      <label @dblclick="editTodo(todo)">{{ todo.title }}</label>
      <button @click="removeTodo(todo)">x</button>
    </div>
    <!-- 编辑待办 -->
    <edit-todo
      v-model:todo-title="todo.title"
      v-todo-focus="todo === editedTodo"
      class="edit"
      @blur="doneEdit(todo)"
      @keyup.enter="doneEdit(todo)"
      @keyup.escape="cancelEdit(todo)"
    />
  </li>
</template>

<script>
import { reactive, toRefs } from "vue";
export default {
  name: "TodoItem",
  directives: {
    "todo-focus": (el, binding) => {
      if (binding.value) {
        el.focus();
      }
    },
  },
  props: {
    todo: {
      type: Object,
      required: true,
    },
    editedTodo: Object,
  },
  emits: ["remove-todo", "update:edited-todo"],
  setup(props, context) {
    const state = reactive({
      beforeEditCache: "", // 缓存编辑前的title
    });

    function removeTodo(todo) {
      context.emit("remove-todo", todo);
    }

    function editTodo(todo) {
      state.beforeEditCache = todo.title;
      context.emit("update:edited-todo", todo);
    }

    function cancelEdit(todo) {
      todo.title = state.beforeEditCache;
      context.emit("update:edited-todo", null);
    }

    function doneEdit(todo) {
      context.emit("update:edited-todo", null);
    }
    return {
      ...toRefs(state),
      removeTodo,
      editTodo,
      cancelEdit,
      doneEdit,
    };
  },
};
</script>

<style scoped>
.completed label {
  text-decoration: line-through;
}

.edit,
.editing .view {
  display: none;
}

.view,
.editing .edit {
  display: block;
}
</style>
